﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Inlycat.Log;

namespace Inlycat
{

    /// <summary>
    /// Author:gouzhun 
    /// 1.cache loaded item
    /// 2.one api to load res from assetbundle , resources folder or local file system
    /// 3.TODO:hot swap
    /// </summary>
    public class ResourcesPool : Singleton<ResourcesPool>
    {
        private static Dictionary<string, Object> m_CachedItems = new Dictionary<string, Object>();

        private static Dictionary<string, string> assetsConfig = new Dictionary<string, string>();

        /// <summary>
        /// private construction for init something
        /// </summary>
        private ResourcesPool() { }

        /// <summary>
        /// so called "one api"
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="path"></param>
        /// <param name="isAbsPath">is whether absolute path which can load from "Resources" folder, default is true</param>
        /// <param name="isCached">cache this res,default is true</param>
        /// <returns></returns>
        public T Load<T>(string path, bool isAbsPath = true, bool isCached = true) where T : Object
        {
            path = path.Replace("\\", "/");
            var assetName = path.Split('/').Last();
            T obj = null;

            if (m_CachedItems.ContainsKey(assetName))
            {
                return (T)m_CachedItems[assetName];
            }


            if (isAbsPath)
            {
                obj = Resources.Load<T>(path);
            }
            else
            {
                if (assetsConfig.ContainsKey(assetName))
                {
                    obj = Resources.Load<T>(assetsConfig[assetName]);
                }
                else
                {
                    PLog.LogError("could not find asset config in assetsConfig named: " + path);
                }
            }

            //cache it if necessary
            if (isCached)
            {
                m_CachedItems.Add(assetName, obj);
            }
            return obj;
        }

        /// <summary>
        /// dispose all the resources in this class's cached collections
        /// </summary>
        public void DisposeAll()
        {
            for (int i = 0; i < m_CachedItems.Keys.Count; i++)
            {
                var obj = m_CachedItems[m_CachedItems.Keys.ElementAt(i)];
                Resources.UnloadAsset(obj);
            }
            m_CachedItems.Clear();
        }

        /// <summary>
        /// dispose the resource with the given name.
        /// </summary>
        /// <param name="itemName">the resource's name</param>
        public void Dispose(string itemName)
        {
            if (m_CachedItems.ContainsKey(itemName))
            {
                Resources.UnloadAsset(m_CachedItems[itemName]);
                m_CachedItems.Remove(itemName);
            }
        }

    }


}